package com.echo.week;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author echo
 * @Description 读写锁案例
 * @Date 2023/10/20.
 * @Version 1.0
 */
public class DemoReentrantReadWriteLock {
    public static volatile  int count = 0;

    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        WriteLock writeLock = new WriteLock(lock);
        ReadLock readLock = new ReadLock(lock);
        for (int i=0;i<3;i++){
            new Thread(writeLock).start();
        }

        for (int i = 0; i <5;i++){
            new Thread(readLock).start();
        }

    }



    public static class WriteLock implements  Runnable{

        ReentrantReadWriteLock writeLock;

        public WriteLock(ReentrantReadWriteLock writeLock) {
            this.writeLock = writeLock;
        }

        @Override
        public void run() {

            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i =0;i<2;i++){
                writeLock.writeLock().lock();//加写锁
                count ++;
                System.out.println("写锁："+count);
                writeLock.writeLock().unlock();
            }
        }
    }

    public static class ReadLock implements Runnable{

        ReentrantReadWriteLock readLock;

        public ReadLock(ReentrantReadWriteLock readLock) {
            this.readLock = readLock;
        }

        @Override
        public void run() {

            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            for (int i =0;i<5;i++){
                readLock.readLock().lock();
                System.out.println("读锁："+count);
                readLock.readLock().unlock();
            }
        }
    }
}
